using AutoMapper;
using SqlSugar;
using SX.BaseService.Repository.Core;
using SX.BaseService.Repository.Entity;
using SX.BaseService.Service;
using SX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SX.BaseService.Service
{
    /// <summary>
	/// SysOrganize服务层
	/// </summary>
    public class SysOrganizeService:DbContext, ISysOrganizeService
    {
        private readonly IRepository<SysOrganizeEntity> _repository;
        private readonly IMapper _mapper;

        public SysOrganizeService(IRepository<SysOrganizeEntity> repository,IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<IApiResult> Add(OrgAddModel model)
        {
            var entity = _mapper.Map<SysOrganizeEntity>(model);
            entity.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            entity.CreateTime = DateTime.Now;
            var res= await _repository.Add(entity);
            if (res<=0)
                return ApiResult.NotOk("新增失败");
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> Delete(string id)
        {
            //删除自己以及下级部门
            var sql = @";with temp as(select * from SysOrganize where id=@id
                union all
                select a.* from SysOrganize a join temp b on a.ParentId=b.Id where b.Id is not null and b.Id <>''
                )
            select STUFF((select ','+id from temp for xml path('')),1,1,'')";
            var str = await Db.Ado.GetStringAsync(sql, new { id = id });
            var ids = str.Split(',').ToList();
            var res= await _repository.Delete(ids);
            if (res <= 0)
                return ApiResult.NotOk("删除失败");
            return ApiResult.Ok();
        }

        public async Task<IApiResult> GetById(string id)
        {
            var res=await _repository.GetId(id);
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> GetTree()
        {
            var list = await _repository.GetAll();
            var treeList = new List<OrgTreeResModel>();
            foreach (var item in list.Where(m => m.ParentId.IsNull()||m.ParentId=="0").OrderBy(m => m.Sort))
            {
                //获得子级
                var children = RecursionOrganize(list.ToList(), new List<OrgTreeResModel>(), item.Id);
                treeList.Add(new OrgTreeResModel()
                {
                    Id = item.Id,
                    Label = item.Name,
                    Spread = children.Count > 0,
                    Children = children.Count == 0 ? null : children
                });
            }
            return ApiResult.Ok(treeList);
        }

        public async Task<IApiResult> Query(OrgQueryModel model)
        {
            RefAsync<int> total = 0;
            var queryable = Db.Queryable<SysOrganizeEntity>();
            var list = new List<SysOrganizeEntity>();
            if (model.Id.IsNull())
            {
                 list =await Db.SqlQueryable<SysOrganizeEntity>("select a.id,a.Name,a.Sort,a.CreateTime,b.Name parentName from SysOrganize a left join SysOrganize b  on a.ParentId=b.Id where 1=1  ").WhereIF(model.Name.NotNull(), x => x.Name.Contains(model.Name)).ToPageListAsync(model.PageIndex, model.PageSize,total);
            }
            else
            {
                var sql = @";with temp as(select * from SysOrganize where id=@id
                union all
                select a.* from SysOrganize a join temp b on a.ParentId=b.Id where b.Id is not null and b.Id <>''
                )
                select*,(select name from SysOrganize where id=temp.ParentId)parentName from temp where 1=1 ";
                list =await Db.SqlQueryable<SysOrganizeEntity>(sql).Where(x=>x.Id==model.Id).WhereIF(model.Name.NotNull(), x => x.Name.Contains(model.Name)).ToPageListAsync(model.PageIndex, model.PageSize,total);
            }
            PageResult<SysOrganizeEntity> result = new PageResult<SysOrganizeEntity>()
            {
                Rows = list,
                TotalCount = total
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> Update(OrgUpdateModel model)
        {
            var entity = _mapper.Map<SysOrganizeEntity>(model);
            var res=await _repository.Update(entity);
            if (res<1)
                return ApiResult.NotOk("更新失败");
            return ApiResult.Ok();
        }

        /// <summary>
        /// 递归部门
        /// </summary>
        /// <param name="sourceList">原数据</param>
        /// <param name="list">新集合</param>
        /// <param name="guid">父节点</param>
        /// <returns></returns>
        List<OrgTreeResModel> RecursionOrganize(List<SysOrganizeEntity> sourceList, List<OrgTreeResModel> list, string id)
        {
            foreach (var row in sourceList.Where(m => m.ParentId == id).OrderBy(m => m.Sort))
            {
                var res = RecursionOrganize(sourceList, new List<OrgTreeResModel>(), row.Id);
                list.Add(new OrgTreeResModel()
                {
                    Id = row.Id,
                    Label = row.Name,
                    Spread = res.Count > 0,
                    Children = res.Count > 0 ? res : null
                });
            }
            return list;
        }
    }
}